package com.pucheng.bracelet.viewmodel

import android.bluetooth.BluetoothGatt
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleGattCallback
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.pucheng.bracelet.app.ble.ClientManager
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.CacheUtil
import com.pucheng.bracelet.data.bean.WatchInfoBean
import com.pucheng.bracelet.ui.adapter.WatchInfoAdapter
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel


class WatchScanViewModel() : BaseViewModel() {

    var bleDevices: MutableList<BleDevice> = arrayListOf()
    var bleDervicesAdp: WatchInfoAdapter = WatchInfoAdapter(bleDevices)
    var connectedWatchInfo = MutableLiveData<WatchInfoBean>()
    var isScanFinished = MutableLiveData<Boolean>().apply {
        value = false
    }

    fun connectBle(mac: String) {

//
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
        LogUtils.e("正在连接：$mac")
        loadingChange.showDialog.value = "正在连接"
        stopScan()
        ClientManager.getInstance().connect(mac, object :
            BleGattCallback() {
            override fun onStartConnect() {
            }

            override fun onDisConnected(
                isActiveDisConnected: Boolean,
                device: BleDevice?,
                gatt: BluetoothGatt?,
                status: Int
            ) {
                LogUtils.e("断开连接：$mac")
            }

            override fun onConnectSuccess(
                bleDevice: BleDevice,
                gatt: BluetoothGatt?,
                status: Int
            ) {
                loadingChange.dismissDialog.value = true
                if (!TextUtils.isEmpty(bleDevice.mac)){
                    val watchInfo = WatchInfoBean(bleDevice.name, bleDevice.mac)
                    CacheUtil.setWatchInfo(watchInfo)
                    if (bleDevice.scanRecord!=null && bleDevice.scanRecord.isNotEmpty()) {
                        CacheUtil.setSupportFunction(ByteUtils.highLowExchangeToInt(ByteUtils.subBytes(
                            bleDevice.scanRecord,
                            18,
                            1
                        )))
                    }
                    connectedWatchInfo.value = watchInfo
                }else{
                    ToastUtils.showShort("连接失败")
                }            }

            override fun onConnectFail(bleDevice: BleDevice?, exception: BleException?) {
                LogUtils.e("连接出错：$exception")
            }
        })
    }

    fun searchDevice() {
        bleDevices.clear()
        if (BleManager.getInstance().bluetoothAdapter != null) {
            LogUtils.e("bondSize${BleManager.getInstance().bluetoothAdapter.bondedDevices.size}")
            for (bondedDevice in BleManager.getInstance().bluetoothAdapter.bondedDevices) {
                if ("I629" == bondedDevice.name) {
                    bleDevices.add(BleDevice(bondedDevice))
                }
            }
//        bleDevices.addAll(BleManager.getInstance().bluetoothAdapter.bondedDevices)
            bleDervicesAdp.notifyDataSetChanged()
        }
        ClientManager.getInstance().startScan(object : BleScanCallback() {
            override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                LogUtils.e("---onScanFinished---")
                isScanFinished.value = true
            }

            override fun onScanStarted(success: Boolean) {

            }

            override fun onScanning(device: BleDevice?) {
                if (bleDevices.indexOfFirst { device!!.mac == it.mac } == -1) {
                    bleDevices.add(device!!)
                }
                bleDervicesAdp.notifyDataSetChanged()
            }
        })
    }

    fun stopScan(){
        BleManager.getInstance().cancelScan()
    }

}